package com.bw.module_detail.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bw.lib_common.base.BaseMVIFragment
import com.bw.module_detail.R
import com.bw.module_detail.adapter.DetailCommentAdapter
import com.bw.module_detail.databinding.FragmentCommentBinding
import com.bw.module_detail.intent.DetailIntent
import com.bw.module_detail.model.entity.CommentEntity
import com.bw.module_detail.state.DetailSimpleState
import com.bw.module_detail.viewmodel.DetailViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class CommentFragment : BaseMVIFragment() {
    private lateinit var mViewModel:DetailViewModel
    private val commentAdapter = DetailCommentAdapter()
    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[DetailViewModel::class.java]
    }
    private val mBinding:FragmentCommentBinding by lazy {
        FragmentCommentBinding.inflate(layoutInflater)
    }

    override fun initView() {
        super.initView()
        mBinding.rvComment.adapter = commentAdapter
        commentAdapter.notifyDataSetChanged()

        // 初始化发送评论的点击监听（新增）
        setupSendCommentListener()
    }

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                // 从Activity获取视频ID
                val videoId = (activity as? com.bw.module_detail.MainActivity)?.itemId ?: ""
                if (videoId.isNotEmpty()) {
                    mViewModel.intents.send(DetailIntent.getCommentList(0, videoId))
                }
            }
        }
    }
    override fun getFragmentRootView(): View {
        return mBinding.root
    }

    // 设置发送评论的监听
    private fun setupSendCommentListener() {
        // 发送按钮点击
        mBinding.btnSendComment.setOnClickListener {
            sendComment()
        }
        // 输入框回车发送（可选优化）
        mBinding.etComment.setOnEditorActionListener { _, _, _ ->
            sendComment()
            true
        }
    }

    // 发送评论核心逻辑
    private fun sendComment() {
        // 1. 校验输入内容
        val commentContent = mBinding.etComment.text.toString().trim()
        if (commentContent.isEmpty()) {
            showMsg("请输入评论内容")
            return
        }

        // 2. 获取视频ID（和请求评论列表一致）
        val videoId = (activity as? com.bw.module_detail.MainActivity)?.itemId ?: ""
        if (videoId.isEmpty()) {
            showMsg("无法获取视频信息，发送失败")
            return
        }

        // 3. 封装评论实体（根据CommentEntity字段赋值，无关字段暂时传默认值）
        val commentEntity = CommentEntity(
            agreenum = 0,          // 初始点赞数0
            content = commentContent,  // 评论内容
            createtime = "",       // 时间由后端生成，前端传空
            datatype = 0,          // 和请求评论列表的datatype一致（这里用0）
            id = 0,                // 新增评论ID由后端生成，前端传0
            itemid = videoId,      // 视频ID
            nickname = "懂博洋", // 替换为实际登录用户名（从MMKV等获取）
            replyList = emptyList(),// 初始无回复
            replytotal = 0,        // 初始回复数0
            userid = 2152,         // 替换为实际登录用户ID（从MMKV等获取）
            userlogo = "" // 替换为实际登录用户头像（从MMKV等获取）
        )

        // 4. 发送评论请求
        lifecycleScope.launch {
            mViewModel.intents.send(DetailIntent.publishComment(commentEntity))
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                launch {
                    mViewModel.commentState_.collect{
                        when(it){
                            is DetailSimpleState.Init ->{

                            }
                            is DetailSimpleState.Empty ->{

                            }
                            is DetailSimpleState.Loading ->{

                            }
                            is DetailSimpleState.Success ->{
                                commentAdapter.setData(it.data)
                            }
                            is DetailSimpleState.Error ->{

                            }
                        }
                    }
                }

                launch {
                    mViewModel.publishCommentState_.collect{
                        when(it){
                            is DetailSimpleState.Loading ->{
                                // 加载中：按钮置灰，防止重复点击
                                mBinding.btnSendComment.isEnabled = false
                                mBinding.btnSendComment.text = "发送中..."
                            }
                            is DetailSimpleState.Success ->{
                                // 成功：清空输入框、刷新评论列表、恢复按钮状态
                                mBinding.etComment.text.clear()
                                showMsg("发送评论成功")
                                val videoId = (activity as? com.bw.module_detail.MainActivity)?.itemId ?: ""
                                if (videoId.isNotEmpty()) {
                                    mViewModel.intents.send(DetailIntent.getCommentList(0, videoId))
                                }
                                mBinding.btnSendComment.isEnabled = true
                                mBinding.btnSendComment.text = "发送"
                            }
                            is DetailSimpleState.Error ->{
                                // 失败：提示错误、恢复按钮状态
                                showMsg("发送失败}")
                                mBinding.btnSendComment.isEnabled = true
                                mBinding.btnSendComment.text = "发送"
                            }
                            else ->{

                            }
                        }
                    }
                }
            }
        }
    }
}